package com.baidu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;

/**
 * 创作时间：2019/10/23 14:48
 * 作者：李增强
 */
@Component
public class EmailSender {

    @Autowired
    private JavaMailSender javaMailSender;

    private static EmailSender emailSender;

    @PostConstruct
    public void init() {
        emailSender = this;
        emailSender.javaMailSender= this.javaMailSender;
    }


    public  void sendSimpleMessage(String sendFrom, String[] sendTo, String subject, String textcontent) {
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setFrom(sendFrom);
        mail.setTo(sendTo);
        mail.setSubject(subject);
        mail.setText(textcontent);
        //发送
        emailSender.javaMailSender.send(mail);
    }

    public void sendHtmlMessage(String sendFrom, String[] sendTo, String subject, String htmlContent) throws Exception {
        MimeMessage mimeMessage = emailSender.javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setFrom(sendFrom);
        mimeMessageHelper.setTo(sendTo);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(htmlContent, true);
        emailSender.javaMailSender.send(mimeMessage);
    }


    public String emailSend(String email,String info){
        String sendFrom="362608691@qq.com";
        String [] sendTo={email};// 接收者邮箱
        String subject="李增强老师邮件测试";//邮件主题
        EmailSender emailSender=new EmailSender();
        StringBuilder htmlContent = new StringBuilder()
                .append("<html>")
                .append("<head>")
                .append("<title>")
                .append("李增强老师邮件测试")
                .append("</title>")
                .append("</head>")
                .append("<body>")
                .append(info+"<p/>")
                .append("</body>")
                .append("</html>");
        try {
            emailSender.sendHtmlMessage(sendFrom, sendTo, subject, htmlContent.toString());
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}